extends MoveElement


class_name NavigationElement


@export var agent: NavigationAgent2D = null
@export var goal_position: Vector2 = Vector2.ZERO: set = seek
@export var seek_interval: float = 0.1


var next_velicity: Vector2 = Vector2.ZERO
var seek_tick: float = 0.0
var is_seeked: bool = false


func __check_exports() -> Dictionary:
    return IComponent.merge({
        "agent": func(): return agent != null,
    }, super.__check_exports())

func __init_hooks() -> Dictionary:
    return IComponent.merge({
        agent.velocity_computed: on_velocity_computed,
    }, super.__init_hooks())

func seek(goal: Vector2) -> void:
    goal_position = goal
    agent.target_position = goal
    seek_tick = 0
    is_enable = true
    is_seeked = true

func move() -> void:
    var next: Vector2 = agent.get_next_path_position()
    move_component.direction = (next - move_component.wrapper.global_position).normalized()
    agent.set_velocity_forced(move_component.direction * move_component.speed)

func on_velocity_computed(safe_velocity: Vector2) -> void:
    next_velicity = safe_velocity

func yield_move(delta: float) -> Vector2:
    if not is_seeked or agent.is_target_reached():
        move_component.stop()
        is_enable = false
        is_seeked = false
        return Vector2.ZERO
    seek_tick += delta
    if seek_tick > seek_interval:
        seek_tick = 0
        move()
    return next_velicity
